#include "aodv.h"
#include "aodv_types.h"
#include "net_interface.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 邻居表最大条目数
#define MAX_NEIGHBOR_ENTRIES 50

// 邻居表全局变量
static neighbor_table_entry_t neighbor_table[MAX_NEIGHBOR_ENTRIES];
static int neighbor_table_count = 0;

// 添加邻居表项
int neighbor_table_add(neighbor_table_entry_t *entry) {
    // 检查邻居表是否已满
    if (neighbor_table_count >= MAX_NEIGHBOR_ENTRIES) {
        printf("Neighbor table is full\n");
        return -1;
    }
    
    // 检查是否已存在相同IP的邻居
    for (int i = 0; i < neighbor_table_count; i++) {
        if (neighbor_table[i].neighbor_ip == entry->neighbor_ip) {
            // 已存在，更新邻居表项
            return neighbor_table_update(entry->neighbor_ip);
        }
    }
    
    // 添加新邻居表项
    memcpy(&neighbor_table[neighbor_table_count], entry, sizeof(neighbor_table_entry_t));
    neighbor_table_count++;
    
    printf("Added neighbor: %d.%d.%d.%d, status: %s\n",
           (entry->neighbor_ip >> 24) & 0xFF, (entry->neighbor_ip >> 16) & 0xFF, 
           (entry->neighbor_ip >> 8) & 0xFF, entry->neighbor_ip & 0xFF,
           entry->status == NEIGHBOR_STATUS_ALIVE ? "ALIVE" : "DEAD");
    
    return 0;
}

// 更新邻居表项
int neighbor_table_update(uint32_t neighbor_ip) {
    for (int i = 0; i < neighbor_table_count; i++) {
        if (neighbor_table[i].neighbor_ip == neighbor_ip) {
            neighbor_table[i].last_hello_time = get_current_time();
            neighbor_table[i].status = NEIGHBOR_STATUS_ALIVE;
            
            printf("Updated neighbor: %d.%d.%d.%d\n",
                   (neighbor_ip >> 24) & 0xFF, (neighbor_ip >> 16) & 0xFF, 
                   (neighbor_ip >> 8) & 0xFF, neighbor_ip & 0xFF);
            
            return 0;
        }
    }
    
    // 邻居不存在，创建新邻居表项
    neighbor_table_entry_t new_neighbor;
    new_neighbor.neighbor_ip = neighbor_ip;
    new_neighbor.hop_count = 1;
    new_neighbor.status = NEIGHBOR_STATUS_ALIVE;
    new_neighbor.last_hello_time = get_current_time();
    
    aodv_config_t *config = aodv_get_config();
    new_neighbor.hello_interval = config ? config->hello_interval : 1000; // 默认1秒
    
    return neighbor_table_add(&new_neighbor);
}

// 查找邻居表项
neighbor_table_entry_t *neighbor_table_find(uint32_t neighbor_ip) {
    for (int i = 0; i < neighbor_table_count; i++) {
        if (neighbor_table[i].neighbor_ip == neighbor_ip) {
            return &neighbor_table[i];
        }
    }
    return NULL;
}

// 删除邻居表项
int neighbor_table_delete(uint32_t neighbor_ip) {
    for (int i = 0; i < neighbor_table_count; i++) {
        if (neighbor_table[i].neighbor_ip == neighbor_ip) {
            // 从邻居表中删除，将最后一个条目移到当前位置
            if (i < neighbor_table_count - 1) {
                memcpy(&neighbor_table[i], &neighbor_table[neighbor_table_count - 1], sizeof(neighbor_table_entry_t));
            }
            neighbor_table_count--;
            
            printf("Deleted neighbor: %d.%d.%d.%d\n",
                   (neighbor_ip >> 24) & 0xFF, (neighbor_ip >> 16) & 0xFF, 
                   (neighbor_ip >> 8) & 0xFF, neighbor_ip & 0xFF);
            
            return 0;
        }
    }
    return -1; // 未找到邻居
}

// 标记邻居为死亡
void neighbor_table_mark_dead(uint32_t neighbor_ip) {
    neighbor_table_entry_t *entry = neighbor_table_find(neighbor_ip);
    if (entry != NULL) {
        entry->status = NEIGHBOR_STATUS_DEAD;
        
        printf("Marked neighbor as dead: %d.%d.%d.%d\n",
               (neighbor_ip >> 24) & 0xFF, (neighbor_ip >> 16) & 0xFF, 
               (neighbor_ip >> 8) & 0xFF, neighbor_ip & 0xFF);
        
        // 处理链路故障
        handle_link_failure(neighbor_ip);
    }
}

// 检查邻居状态
void check_neighbor_status(void) {
    uint32_t current_time = get_current_time();
    aodv_config_t *config = aodv_get_config();
    uint32_t hello_loss_timeout = config ? 
        (config->hello_interval * (config->allowed_hello_loss + 1)) : 3000; // 默认3秒
    
    for (int i = 0; i < neighbor_table_count; i++) {
        neighbor_table_entry_t *entry = &neighbor_table[i];
        if (entry->status == NEIGHBOR_STATUS_ALIVE) {
            // 检查是否超时未收到HELLO消息
            if (current_time - entry->last_hello_time > hello_loss_timeout) {
                printf("Neighbor timeout: %d.%d.%d.%d\n",
                       (entry->neighbor_ip >> 24) & 0xFF, 
                       (entry->neighbor_ip >> 16) & 0xFF, 
                       (entry->neighbor_ip >> 8) & 0xFF, 
                       entry->neighbor_ip & 0xFF);
                
                // 标记邻居为死亡
                neighbor_table_mark_dead(entry->neighbor_ip);
            }
        }
    }
}

// 发送HELLO消息
void send_hello_message(void) {
    // HELLO消息实际上是特殊的RREP消息，目标IP为广播地址
    rrep_message_t rrep;
    rrep.type = MESSAGE_TYPE_RREP;
    rrep.flags = 0; // 标准HELLO消息不需要标志位
    rrep.prefix_size = 0;
    rrep.hop_count = 0;
    rrep.destination_ip = net_interface_get_my_ip(); // 源节点自己的IP
    rrep.destination_seq_num = 0; // HELLO消息中序列号意义不大
    rrep.source_ip = net_interface_get_my_ip();
    rrep.lifetime = 0; // HELLO消息中生存时间意义不大
    
    // 广播HELLO消息
    net_interface_broadcast(PROTOCOL_AODV, (void *)&rrep, sizeof(rrep_message_t));
    printf("Sent HELLO message\n");
}

// 打印邻居表
void aodv_print_neighbor_table(void) {
    printf("\n=== Neighbor Table (%d entries) ===\n", neighbor_table_count);
    printf("%-15s %-8s %-10s %-15s\n",
           "Neighbor IP", "Hop Count", "Status", "Last Hello");
    
    for (int i = 0; i < neighbor_table_count; i++) {
        neighbor_table_entry_t *entry = &neighbor_table[i];
        printf("%d.%d.%d.%d  %-8u %-10s %u\n",
               (entry->neighbor_ip >> 24) & 0xFF, 
               (entry->neighbor_ip >> 16) & 0xFF, 
               (entry->neighbor_ip >> 8) & 0xFF, 
               entry->neighbor_ip & 0xFF,
               entry->hop_count,
               entry->status == NEIGHBOR_STATUS_ALIVE ? "ALIVE" : "DEAD",
               entry->last_hello_time);
    }
    printf("=============================\n\n");
}